import PrinterJobs from '@/static/js/print/printerjobs.js'
import $config from '@/config/index.js'

export default {
	print($store,context,pW,pH){
		const _myBlue = $store.getters['print/getBlueInfo'];
		if (_myBlue) {
			return this.sendBlueToothData($store,context,_myBlue,pW,pH)
		} else {
			return new Promise((resolve)=>{
				uni.navigateTo({
					url: $config.path.bluetooth
				});
				resolve()
			})
		}
	},
	sendBlueToothData($store,context,blueInfo,pW=570,pH=400){
		return new Promise((resolve,reject)=>{
			uni.showLoading({
				title: '蓝牙数据传输中',
				mask:true
			});
			/* 
				尺寸换算：1mm=8单位
			 label_set_page  参数：宽（最大576）、高
			 drawLine  参数：线宽、起始点x、起始点y、结束点x、结束点y
			 drawText  参数：起始点x、起始点y、文字、字体大小、旋转角度、粗体(0否1是)、下划线、反白
			          字体大小：可选值 20/1/2/3/4/5/6/7 ，其他的时候默认为2
								旋转角度：0-不选择/1-90度/2-180度/3-270度
			 drawQrCode 二维码，参数：起始点x、起始点y、二维码内容、旋转参数恒定为0、二维码宽度(2-15)、二维码纠错等级(0-20)
			 drawBarCode 条形码，参数:起始点x、起始点y、条形码内容、条形码类型、旋转参数恒定为0、条码宽度(2~6)、条码高度(1~255)
								条形码类型： 0：CODE39；1：CODE128；2：CODE93；3：CODEBAR；4：EAN8；5：EAN13；6：UPCA; 7:UPC-E; 8:ITF
			 */
			let printerJobs = new PrinterJobs();
			printerJobs.label_set_page(pW, pH);
			context.forEach((contextItem)=>{
				switch(contextItem.type) {
					case 'line':
						printerJobs.drawLine(contextItem.width,contextItem.x1,contextItem.y1,contextItem.x2,contextItem.y2);
						break;
					case 'text':
						printerJobs.drawText(contextItem.x,contextItem.y,contextItem.text,contextItem.size,contextItem.rotate,contextItem.bold,contextItem.underline,contextItem.reverse);
						break;
					case 'qr':
						printerJobs.drawQrCode(contextItem.x,contextItem.y,contextItem.text,0,contextItem.width,contextItem.level);
						break;
					case 'bar':
						printerJobs.drawBarCode(contextItem.x,contextItem.y,contextItem.text,contextItem.barType,0,contextItem.width,contextItem.height);
						break;
					default:
						break;
				}
			})
			printerJobs.label_print(0, 1);
			let buffer = printerJobs.buffer();	
			this.bufferTransmission(buffer,$store,blueInfo).then((res)=>{
				resolve(res)
			}).catch((err)=>{
				reject(err)
			})
		})
	},
	bufferTransmission(buffer,$store,blueInfo){
		return new Promise((resolve,reject)=>{
			if (blueInfo===undefined) blueInfo = $store.getters['print/getBlueInfo'];
			let deviceId = blueInfo.deviceId
			let serviceId = blueInfo.serviceId
			let characteristicId = blueInfo.characteristicId
			
			const maxChunk = 20;
			const delay = 15;
			let length = buffer.byteLength;
			let pakageLen = Math.trunc(length/maxChunk);
			if (length%maxChunk!==0) pakageLen=pakageLen+1;
			console.log(`共${length}字节，分${pakageLen}包`)
		  
			//超时设置
			const _timeOutNum = 30 * 1000;
			const _sendTimeOut = setTimeout(()=>{
				let tMsg = `蓝牙数据传输超时，${_sendTimeOut/1000}秒内无响应！`
				uni.hideLoading();
				this.researchConfirm(tMsg)
				reject(tMsg)
			},_timeOutNum)
			
			//判断传输顺序是否正确
			const isRightTransferOrder = function(arr){
				let __res = true;
				for (let _i=0;_i<(arr.length-1);_i++) {
					if (arr[_i]>=arr[_i+1]) {
						__res = false;
						break;
					}
				}
				return __res
			}
			
			let successArr = [];
			for (let i = 0, j = 0; i < length; i += maxChunk, j++) {
				let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
				//_count = j;
				setTimeout(() => {
					console.log(`第${j+1}分包发送，开始字节${i}`)
					this._writeBLECharacteristicValue(deviceId, serviceId, characteristicId, subPackage,(f)=>{
						console.log(`第${j+1}返回${f}`)
						if (f) {
							successArr.push(j+1)
						}
						// 最后1个包返回，则：
						if (j===pakageLen-1) {
							uni.hideLoading();
							let successLen = successArr.length;
							let modalMsg = `蓝牙传输分${pakageLen}包，成功传输${successLen}个包`
							if (successLen) {
								modalMsg += `，依次为：${successArr.join(",")}。`
							} else {
								modalMsg += '。'
							}
							
							clearTimeout(_sendTimeOut)
							//成功发送的包数量与拆分包数量相等，且成功发送包的顺序正确，认为蓝牙传输正确
							if (pakageLen !==0 && successLen===pakageLen && isRightTransferOrder(successArr)) {
								uni.hideLoading();
								this.alert(modalMsg)
								resolve()
							} else {
								uni.hideLoading();
								this.researchConfirm(modalMsg)
								reject(modalMsg)
							}
						}
					})
				},  j * delay);
			}
			/* promise end */
		})
	},
	_writeBLECharacteristicValue(deviceId, serviceId, characteristicId, buffer,callback){
		uni.writeBLECharacteristicValue({
			deviceId: deviceId,
			serviceId: serviceId,
			characteristicId: characteristicId,
			value: buffer,
			success(res) {
				callback && callback(true)
			},
			fail(res) {
				callback && callback(false)
			}
		})
	},
	alert(msg){
		uni.showModal({
			title:'系统提示',
			content:msg,
			showCancel:false,
			confirmText:'确 定'
		})
	},
	researchConfirm(msg){
		uni.showModal({
			title:'系统提示',
			content:msg,
			cancelText:'取 消',
			confirmText:'重置蓝牙',
			success:(res)=>{
				if (res.confirm) {
					uni.navigateTo({
						url: $config.path.bluetooth + '?again=1'
					});
				}
			}
		})
	},
	getBlueToothes(){
		return new Promise((resolve,reject)=>{
			uni.showLoading({
				title: '启动蓝牙功能',
				mask:true
			});
			uni.getSystemInfo({
				success:function(resfirst){
					if (resfirst.uniPlatform!=='web') {
						try{
							uni.openBluetoothAdapter({
								success:function(){
									uni.showLoading({
										title: '开始搜索蓝牙',
										mask:true
									});
									uni.startBluetoothDevicesDiscovery({
										success:function(){
											uni.showLoading({
												title: '搜索中...',
												mask:true
											});
											let result = [];
											uni.onBluetoothDeviceFound(function(res){
												if (res && res.devices && res.devices.length>0) {
													res.devices.forEach(function(item){
														if (item.name) {
															let addFlag = true;
															for (let i=0;i<result.length;i++) {
																if (item.deviceId===result[i].deviceId) {
																	addFlag = false;
																	break;
																}
															}
															if (addFlag) {
																result.push(item)
															}
														}
													})
												}
											})
											setTimeout(function(){
												uni.stopBluetoothDevicesDiscovery({
													success:function(){
														uni.hideLoading();
														resolve(result)
													},
													fail:function(){
														uni.hideLoading();
														reject('关闭蓝牙搜索失败')
													}
												})
											},5*1000)
										},
										fail:function(){
											uni.hideLoading();
											reject('开启蓝牙搜索失败')
										}
									})
								},
								fail:function(){
									uni.hideLoading();
									reject('蓝牙模块启动失败')
								}
							})
						}catch(e){
							uni.hideLoading();
							reject(e)
						}
					} else {
						uni.hideLoading();
						reject('Web无效！')
					}
				},
				fail:function(errfirst){
					uni.hideLoading();
					reject(errfirst)
				}
			})
		})
	},
	reGetBlueToothes($store){
		return new Promise((resolve,reject)=>{
			uni.closeBluetoothAdapter({
				complete:()=>{
					this.getBlueToothes().then(res => {
						resolve(res)
					}).catch(err=>{
						reject(err)
					})
				}
			})
		})
	},
	connect($store,id){
		return new Promise(function(resolve,reject){
			uni.showLoading({
				title: '连接中...',
				mask:true
			});
			uni.closeBLEConnection({
				deviceId:id,
				complete:()=>{
					uni.createBLEConnection({
						 deviceId:id,
						 success:function(){
							$store.commit('print/setDeviceId',id)
							uni.showLoading({
								title: '获取蓝牙服务',
								mask:true
							});
							setTimeout(function(){
								uni.getBLEDeviceServices({
									deviceId:id,
									success:function(res1){
										let serviceId = '';
										for (let i=0;i<res1.services.length;i++){
											if (res1.services[i].uuid.indexOf("FF00") !== -1) {
												serviceId = res1.services[i].uuid;
												break;
											}
										}
										if (serviceId) {
											uni.showLoading({
												title: '获取服务特征值',
												mask:true
											});
											uni.getBLEDeviceCharacteristics({
												deviceId:id,
												serviceId:serviceId,
												success:function(res2){
													let characteristicId = ''
													for (let j=0;j<res2.characteristics.length;j++){
														if (res2.characteristics[j].uuid.indexOf("FF02") !== -1) {
															characteristicId = res2.characteristics[j].uuid;
															break;
														}
													}
													if (characteristicId) {
														let blueInfoObj = {
															deviceId:id,
															serviceId:serviceId,
															characteristicId:characteristicId
														}
														$store.commit('print/setBlueInfo',blueInfoObj);
														uni.showToast({
															title:'蓝牙连接成功',
															icon:'success'
														})
														uni.hideLoading();
														resolve()
													} else {
														uni.hideLoading();
														reject(`获取蓝牙设备${id}的服务特征值不正确`)
													}
												},
												fail:function(){
													uni.hideLoading();
													reject(`获取蓝牙设备${id}的服务特征值失败`)
												}
											})
										} else {
											uni.hideLoading();
											reject(`获取蓝牙设备${id}的服务不正确`)
										}
									},
									fail:function(){
										uni.hideLoading();
										reject(`获取蓝牙设备${id}的服务失败`)
									}
								})
							},1200)
						 },
						 fail:function(){
							uni.hideLoading();
							reject(`创建与蓝牙设备${id}的连接失败`)
						 }
					})
				}
			})	 
		})
	}
}